/*
 * @Description:
 * @Autor: qsyj
 * @Date: 2023-01-03 14:39:21
 * @LastEditors: qsyj
 * @LastEditTime: 2023-03-13 15:23:09
 */

import {
  jsonHttpCodeEnum
} from "./json-code";

// 自定义 响应 拦截器
export function transformResponse( response = {}, options = {} ) {
  // 处理没有响应状态的，有传 true
  const {
    isTransformResponse = false
  } = options;

  if ( !isTransformResponse ) return response;

  const {
    data
  } = response;

  const {
    code,
    message: msg
  } = data;
  // console.log( data, 'data' );
  // switch 判断 状态码 是否为 200
  switch ( String( code ) ) {
    // 是， 全部返回
    case jsonHttpCodeEnum.SUCCESS: {
      // message(msg);
      // return response;
      return data
    };
    // 否则，人为抛出一个错误
    default: {

      uni.showToast( {
        title: msg,
        icon: 'error'
      } )
      throw Error( msg );
    }
  }
}

// 自定义 请求 拦截器
export function tranformRequest( request = {}, option = {} ) {
  const {
    isTranformRequest = true
  } = option;
  const {
    headers = {}
  } = request;

  if ( !isTranformRequest ) return request;

  const _headers = {
    ...headers,
  };

  return {
    ...request,
    headers: _headers
  };
}

export function message( msg ) {
  uni.showToast( {
    title: msg,
    icon: "none",
    duration: 1500
  } );
}